package com.stylefeng.guns.poi.pl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;


/**
 * @author void
 * createDate 2018年9月14日
 * poi 常用操作工具类
 */
public class PoiUtils {
	
	/**
	 * 生成word模板
	 * @param path 模板路径
	 * @param tlName 模板名称
	 * @param datasource 数据源
	 * @return 
	 */
	public static ResponseEntity<byte[]> grWordTl(String tlPath, String drPath, Object datasource){
		
		return grWordTl(tlPath, drPath, datasource, null);
	}
	
	public static ResponseEntity<byte[]> grWordTl(String tlPath, String drPath, Object datasource, Configure config){
		try {
			//如果不存在则生成word模板
			if(!FileUtils.judeFileExists(drPath)){
				grWord(tlPath, drPath, datasource, config);
			}else{
				//存在的话判断是否覆盖生成 默认false
				if(PoiConfig.isCover){
					grWord(tlPath, drPath, datasource, config);
				}
			}
			
	        return getResponEntity(drPath);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static ResponseEntity<byte[]> getResponEntity(String drPath) throws IOException{
		File file = new File(drPath);
        byte[] body = null;
        InputStream is = new FileInputStream(file);
        body = new byte[is.available()];
        is.read(body);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attchement;filename=" + new String(file.getName().getBytes(), "ISO-8859-1"));
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        is.close();
        return entity;
	}
	
	public static void grWord(String tlPath, String drPath, Object datasource) throws IOException{
		grWordTl(tlPath, drPath, datasource, null);
	}
	
	public static void grWord(String tlPath, String drPath, Object datasource, Configure config)throws IOException{
		FileUtils.makeFolders(drPath);
		XWPFTemplate template = null;
		System.out.println(tlPath);
		if(null != config){
			template = XWPFTemplate.compile(tlPath, config).render(datasource);
		}else{
			template = XWPFTemplate.compile(tlPath).render(datasource);
		}
        FileOutputStream out = new FileOutputStream(drPath);
		template.write(out);
        out.flush();
        out.close();
        template.close();
	}
}
